package com.hyjx.framework.uc.user;

import com.hyjx.framework.common.tree.TreeObject;
import com.hyjx.framework.common.tree.TreeUtil;
import com.hyjx.framework.common.tree.ZTreeNode;
import com.hyjx.framework.common.util.MD5Helper;
import com.hyjx.framework.common.util.SpringBeanUtil;
import com.hyjx.framework.common.util.StringHelper;
import com.hyjx.framework.service.RightManager;
import com.hyjx.framework.service.UserCenterService;
import com.hyjx.framework.service.extend.IUserExtend;
import com.hyjx.framework.uc.admin.AdminModel;
import com.hyjx.framework.uc.admin.AdminService;
import com.hyjx.framework.uc.role.RoleModel;
import com.hyjx.framework.uc.role.RoleService;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 * 用户控制器
 *
 * @author Peter
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService service;
    @Resource
    private AdminService adminService;
    @Resource
    private RoleService roleService;

    /**
     * 跳转到列表页
     *
     * @return
     */
    @RequestMapping(value = "/gotoUserList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ModelAndView gotoUserList(HttpServletRequest request) {
        String departId = request.getParameter("departId");
        String departCode = request.getParameter("departCode");
        String orgCode = request.getParameter("orgCode");
        UserBean bean = new UserBean();
        bean.setDepartId(departId);
        bean.setOrgCode(orgCode);
        bean.setDepartCode(departCode);
        bean.setIsOrg("1");

        ModelAndView mav = new ModelAndView("/framework/uc/user/userlist");
        mav.addObject("bean", bean);
        return mav;
    }

    /**
     * 跳转到列表页
     *
     * @return
     */
    @RequestMapping(value = "/gotoList", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView gotoList() {
        ModelAndView mav = new ModelAndView("/framework/uc/user/list");
        mav.addObject("userOrgCode", UserCenterService.getCurrentUserInfo().getDataOrgCode());
        return mav;
    }

    /**
     * 跳转到选择列表页
     *
     * @return
     */
    @RequestMapping(value = "/gotoSelectList", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ModelAndView gotoSelectList(HttpServletRequest request) {
        String orgCode = request.getParameter("orgCode");
        if (orgCode == null) {
            orgCode = UserCenterService.getCurrentUserInfo().getOrg_code();
        }
        String departCode = orgCode;

        UserBean bean = new UserBean();
        bean.setOrgCode(orgCode);
        bean.setDepartCode(departCode);

        ModelAndView mav = new ModelAndView("/framework/uc/user/selectlist");
        mav.addObject("bean", bean);
        return mav;
    }

    /**
     * 获取列表信息
     *
     * @return
     */
    @RequestMapping(value = "/queryUserList", produces = "application/json; charset=utf-8", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String queryUserList(UserBean bean) {
        return service.getUsers(bean);
    }

    /**
     * 跳转到增加页
     *
     * @return
     */
    @RequestMapping(value = "/gotoAdd", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ModelAndView gotoAdd(HttpServletRequest request) {
        String optType = request.getParameter("optType");
        String orgCode = null;
        String departCode = null;
        String departId = null;
        String userId = null;
        UserModel model = null;
        if ("2".equals(optType)) {
            userId = request.getParameter("userId");
            model = service.getUserById(userId);
            String roleIds = service.getUserRoleStr(userId);
            model.setRoleIds(roleIds);
            model.setPwdOld(model.getUser_pwd());
            orgCode = model.getOrg_code();
            departCode = model.getDepart_code();
        } else {
            orgCode = request.getParameter("orgCode");
            departCode = request.getParameter("departCode");
            departId = request.getParameter("departId");

            model = new UserModel();
            model.setDepart_code(departCode);
            model.setDepart_id(departId);
            model.setOrg_code(orgCode);
            model.setValidity("Y");
            model.setUser_id(StringHelper.getPrimaryKey());
            model.setCreate_time(new Date());
            model.setUpdate_time(new Date());
        }
        model.setOrgName(RightManager.getOrgNameByCode(orgCode));
        model.setDepartName(RightManager.getDepartByCode(departCode).getDepart_name());
        List<RoleModel> list = roleService.queryRoleListByOrgCode(orgCode);
        StringBuffer sb = new StringBuffer();
        sb.append("[");
        for (int i = 0; i < list.size(); i++) {
            RoleModel rm = list.get(i);
            if (i == 0) {
                sb.append("{'id':'" + rm.getRole_id() + "','name':'" + rm.getRole_name() + "'}");
            } else {
                sb.append(",{'id':'" + rm.getRole_id() + "','name':'" + rm.getRole_name() + "'}");
            }
        }
        sb.append("]");
        model.setOrgRoles(sb.toString());
        ModelAndView mav = new ModelAndView("/framework/uc/user/add");
        mav.addObject("model", model);
        mav.addObject("optType", optType);
        return mav;
    }

    /**
     * 增加信息
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/doAdd", produces = "text/html; charset=utf-8", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String doAdd(UserModel model) {
        IUserExtend userExtendService = (IUserExtend) SpringBeanUtil.getBean("userExtendService");
        if (!userExtendService.isUserAccountUnique(model.getUser_id(), model.getUser_account())) {
            return "notunique";
        }
        if ("admin".equalsIgnoreCase(model.getUser_account())) {
            return "noadmin";
        }
        model.setCreate_time(new Date());
        //model.setUpdate_time(new Date());
        try {
            model.setUser_pwd(MD5Helper.encrypt(model.getUser_pwd()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        IUserExtend userExtend = (IUserExtend) SpringBeanUtil.getBean("userExtendService");
        userExtend.beforeAdd(model);
        if (service.add(model)) {
            userExtend.afterAdd(model);
            RightManager.init(4);
            return "success";
        } else {
            return "failure";
        }
    }

    /**
     * 修改信息
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/doEdit", method = RequestMethod.POST)
    @ResponseBody
    public String doEdit(UserModel model) {
        model.setUpdate_time(new Date());
        if (!"".equals(model.getUser_pwd())) {
            try {
                model.setUser_pwd(MD5Helper.encrypt(model.getUser_pwd()));
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }
        IUserExtend userExtend = (IUserExtend) SpringBeanUtil.getBean("userExtendService");
        userExtend.beforeUpdate(model);
        if (service.update(model) > 0) {
            userExtend.afterUpdate(model);
            RightManager.init(4);
            return "success";
        } else {
            return "failure";
        }
    }

    /**
     * 取对应关系串
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/doUserRole", method = RequestMethod.POST)
    @ResponseBody
    public String doUserRole(HttpServletRequest request) {
        String userId = request.getParameter("id");
        String returnStr = service.getUserRoleStr(userId);
        return returnStr;
    }

    /**
     * 信息查看
     * request
     *
     * @return
     */
    @RequestMapping(value = "/gotoView", method = RequestMethod.GET)
    public ModelAndView gotoView(HttpServletRequest request) {
        String user_id = request.getParameter("user_id");

        UserModel model = service.getUserById(user_id);
        model.setOrgName(RightManager.getOrgNameByCode(model.getOrg_code()));
        model.setDepartName(RightManager.getDepartByCode(model.getDepart_code()).getDepart_name());
        model.setRoleIds(service.getUserRoleStr(user_id));
        List<RoleModel> list = roleService.queryRoleListByOrgCode(RightManager.getUserDataOrgCode(model.getOrg_code()));
        StringBuffer sb = new StringBuffer();
        sb.append("[");
        for (int i = 0; i < list.size(); i++) {
            RoleModel rm = list.get(i);
            if (i == 0) {
                sb.append("{'id':'" + rm.getRole_id() + "','name':'" + rm.getRole_name() + "'}");
            } else {
                sb.append(",{'id':'" + rm.getRole_id() + "','name':'" + rm.getRole_name() + "'}");
            }
        }
        sb.append("]");
        model.setOrgRoles(sb.toString());

        String aa = RightManager.getUserOrgs(user_id);
        model.setOrgCodes(aa);
        model.setMenuCodes(RightManager.getUserMenus(user_id));
        ModelAndView mav = new ModelAndView("/framework/uc/user/view");
        mav.addObject("model", model);
        return mav;
    }

    /**
     * 删除信息
     * request
     *
     * @return
     */
    @RequestMapping(value = "/gotoDelete", method = RequestMethod.GET)
    @ResponseBody
    public String gotoDelete(HttpServletRequest request) {
        String ids = request.getParameter("ids");
        IUserExtend userExtend = (IUserExtend) SpringBeanUtil.getBean("userExtendService");
        userExtend.beforeDelete(ids);
        if (service.logic_delete(ids) > 0) {
            userExtend.afterDelete(ids);
            RightManager.init(4);
            return "success";
        } else {
            return "failure";
        }
    }

    /**
     * 跳转 修改密码
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/editpwd")
    public ModelAndView editpwd(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("/framework/uc/user/editpwd");
        mav.addObject("username", UserCenterService.getCurrentUserInfo().getUser_name());
        return mav;
    }

    /**
     * 修改密码
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/doeditpwd", method = RequestMethod.POST)
    @ResponseBody
    public String doeditpwd(HttpServletRequest request) {
        String old_pwd = request.getParameter("old_pwd");
        String new_pwd = request.getParameter("new_pwd");
        String new_pwd2 = request.getParameter("new_pwd2");

        if (StringUtils.isEmpty(new_pwd)) {
            return "-2";
        }
        if (!new_pwd.equals(new_pwd2)) {
            return "-3";
        }

        UserModel um = new UserModel();
        um.setUser_id(UserCenterService.getCurrentUserInfo().getUser_id());
        um.setUser_account(UserCenterService.getCurrentUserInfo().getUser_account());
        try {
            um.setUser_pwd(MD5Helper.encrypt(old_pwd));
            if (!UserCenterService.getCurrentUserInfo().isSuperAdmin()) {
                um = service.login(um);
                if (um != null) {
                    UserModel um2 = new UserModel();
                    um2.setUser_id(UserCenterService.getCurrentUserInfo().getUser_id());
                    um2.setUser_pwd(MD5Helper.encrypt(new_pwd));
                    service.updatepwd(um2);
                    RightManager.init();
                } else {
                    return "-1";
                }
            } else {
                AdminModel am = new AdminModel();
                am.setAdmin_account(UserCenterService.getCurrentUserInfo().getUser_account());
                List<AdminModel> ams = adminService.queryModelList(am);
                if (ams != null && ams.size() > 0 && ams.get(0).getAdmin_pwd().equalsIgnoreCase(MD5Helper.encrypt(old_pwd))) {
                    am.setAdmin_pwd(MD5Helper.encrypt(new_pwd));
                    adminService.updatepwd(am);
                    RightManager.init();
                } else {
                    return "-1";
                }
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 返回ztree结构的Json字符串
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/usertree", produces = "application/json; charset=utf-8")
    public String usertree(HttpServletRequest request) {
        String orgCode = request.getParameter("rootid");
        String checked = request.getParameter("checked");
        if (checked == null) {
            checked = "";
        }
        if (orgCode == null || "".equals(orgCode)) {
            orgCode = UserCenterService.getCurrentUserInfo().getDataOrgCode();
        }
        String departType = request.getParameter("departtype");
        if (departType == null || "".equals(departType)) {
            departType = "2";
        }

        List<ZTreeNode> list = RightManager.getUsersTreeByOrgCode(departType, orgCode, checked);
        JSONArray jsonArray = JSONArray.fromObject(list);

        String result = jsonArray.toString();
        return result;
    }

    /**
     * 返回easyui tree结构的Json字符串
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/easyuiusertree", produces = "application/json; charset=utf-8")
    public String easyuiusertree(HttpServletRequest request) {
        String orgCode = request.getParameter("rootid");
        String checked = request.getParameter("checked");
        if (checked == null) {
            checked = "";
        }
        if (orgCode == null || "".equals(orgCode)) {
            orgCode = UserCenterService.getCurrentUserInfo().getOrg_code();
        }
        String departType = request.getParameter("departtype");
        if (departType == null || "".equals(departType)) {
            departType = "2";
        }

        List<TreeObject> list = RightManager.getEasyuiUsersTreeByOrgCode(departType, orgCode);
        List<UserModel> ulist = RightManager.getUsersByOrgCode(departType, orgCode);
        for (TreeObject dobject : list) {
            if (dobject.getParent_id().equals("#")) {
                orgCode = dobject.getId();
            }
        }
        for (UserModel model : ulist) {
            TreeObject tree = new TreeObject();
            tree.setId(model.getUser_id());
            tree.setCode(model.getUser_id());
            tree.setText(model.getUser_name());
            tree.setAttributes("true");
            if ("1".equals(departType)) {
                tree.setParent_id(model.getOrg_id());
            } else {
                tree.setParent_id(model.getDepart_id());
            }

            list.add(tree);
        }
        //添加人员节点
        String result = TreeUtil.getEasyuiJsonStr(list, orgCode, checked);
        return result;
    }

}